package com.store.app.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.hyphenate.easeui.widget.EaseSwitchButton;
import com.store.app.BaseActivity;
import com.store.app.ExitApplication;
import com.store.app.MainActivity;
import com.store.app.R;
import com.store.app.adapter.AddGoodsRVAdapter;
import com.store.app.bean.BitmapBean;
import com.store.app.bean.GoodsDetailsNewBean;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.utils.SettingData;
import com.store.app.widget.RecycleViewDivider;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/12/15.
 * 商品详情页面，可编辑
 */
public class GoodDetailsNewActivity extends BaseActivity implements View.OnClickListener, IOnHttpListener {
//    private TextView tv_submit;                                     //提交
//    private EditText et_name;                                       //名称
//    private EditText et_barcode;                                    //条码
//    private Spinner spinner;                                        //分类
//    private EditText et_spec;                                       //规格
//    private EditText et_stock;                                      //库存
//    private EditText et_price;                                      //售价
//    private EditText et_time_call;                                  //临期预警
//    private EditText et_cost;                                       //进价
//    private EditText et_return_money;                               //返利
//    private EditText et_shelf_life;                                 //保质期
//    private EditText et_stock_call;                                 //库存预警
//    private EditText et_vender;                                     //厂家
//    private EditText et_dealer;                                     //经销商
//    private CheckBox cb_recommend;                                    //是否推荐
//    private EaseSwitchButton sw_stop_sell;                                    //是否停止销售
//    private CheckBox cb_weight;                                       //是否称重计量
//    private TextView tv_expiration_date;                            //生产日期
//    private TextView tvTitle;                                       //标题
//    private TextView tv_data_input;                                 //数据导入
//    private ImageView public_ll_return;                             //返回
//    private ImageView iv_pic;                                       //图片
//    private String doc_id;                                          //图片id
//    private String goodsCategory;                                   //商品类别
//    private BitmapBean bitmapBean;
//    private NetRequest netRequest;
//    private Dialog dialog;
//
//    private static final int FLAG_CHOOSE_IMG = 5;
//    private static final int FLAG_CHOOSE_PHONE = 6;
//    private static String localTempImageFileName = "";
//    private static final int FLAG_DETIALS = 99;
//
//    private List<String> keyData = new ArrayList<String>();
//    private List<String> valueData = new ArrayList<String>();
//    private List<Map<String, String>> mDatas = new ArrayList<Map<String, String>>();
//
//    private GoodsBean bean;
//    private String barcode;
//

//    private GoodsDetailsNewBean goodsDetailsNewBean;
//    private RelativeLayout rl_details;
//    private String desc1;//详情描述
//    private String image_detail;//图片详情


    private Map<String, String> map;//图片map;
    private GoodsDetailsNewBean goodsDetailsNewBean;
    private NetRequest netRequest;
    private String item_store_id;
    private TextView tv_zbm;                        //自编码
    private TextView tv_barcode;                    //条形码
    private TextView tv_zjm;                        //助记码
    private TextView tv_name;                       //名称
    private TextView tv_type;                       //品类
    private TextView tv_vender;                     //厂家/品牌
    private TextView tv_sale_unit;                  //销售单位
    private TextView tv_purchase_unit;              //采购单位
    private TextView tv_min_package_unit;           //最小包装
    private TextView tv_conversion_relation;        //换算关系
    private RelativeLayout ll_conversion;
    private TextView tv_bzq;                        //保质期
    private TextView tv_clw;                        //陈列位
    private TextView tv_stock;                      //库存
    private TextView tv_unit;                       //单位
    private TextView tv_cost;                       //进价
    private TextView tv_purchase_price_specifications;//进价规格
    private TextView tv_price;                      //售价
    private TextView tv_price_specifications;       //售价规格
    private TextView tv_return_money;               //返利
    private TextView tv_discount;                   //折扣
    private TextView tv_gross_profit;               //毛利
    private TextView tv_ljyq;                       //临期预警
    private TextView tv_stock_call;                 //库存预警
    private EaseSwitchButton sw_to_cashier;                                   //是否收藏到收银台
    private EaseSwitchButton sw_to_local_life;                                //是否收藏到网店（本地生活）
    private EaseSwitchButton sw_discount;                                     //是否允许折扣
    private TextView tv_buhuo;                      //补货
    private TextView tv_pandian;                    //盘点
    private TextView tv_kaishou;                    //开售
    private TextView tvTitle;
    private ImageView public_ll_return;
    private CheckBox cb_weight;                     //称重计量
    private TextView public_tv_right;
    private EaseSwitchButton sw_to_ad_recommend;    //是否广告推荐
    private RecyclerView rv_show_goods_pic;
    private List<BitmapBean> mUploadBitmapBeans;    //图片列表
    private AddGoodsRVAdapter mAddGoodsRVAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ExitApplication.getInstance().addActivity(this);
        setContentView(R.layout.activity_goods_detail_xgp);
        if (getIntent() != null) {
            if (getIntent().getStringExtra("item_store_id") != null) {
                item_store_id = getIntent().getStringExtra("item_store_id");
            }
        }
        initView();
        initData();
        initRecyclerView();
    }

    private void initRecyclerView() {
        mUploadBitmapBeans = new ArrayList<>();
        rv_show_goods_pic.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        rv_show_goods_pic.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.VERTICAL, 10, Color.WHITE));
        mAddGoodsRVAdapter = new AddGoodsRVAdapter(this, mUploadBitmapBeans);
        rv_show_goods_pic.setAdapter(mAddGoodsRVAdapter);
    }

    private void initData() {
        tvTitle.setText("商品详情");
        netRequest = new NetRequest(this);
        showProgressDialog("", "数据加载中...");
        netRequest.requestGoodsDetails(4, item_store_id);

    }

    private void initView() {
        public_ll_return = (ImageView) findViewById(R.id.public_ll_return);
        tvTitle = (TextView) findViewById(R.id.tvTitle);
        sw_to_cashier = (EaseSwitchButton) findViewById(R.id.sw_to_cashier);
        sw_to_local_life = (EaseSwitchButton) findViewById(R.id.sw_to_local_life);
        sw_discount = (EaseSwitchButton) findViewById(R.id.sw_discount);
        public_ll_return.setOnClickListener(this);


        tv_zbm = (TextView) findViewById(R.id.tv_zbm);
        tv_barcode = (TextView) findViewById(R.id.tv_barcode);
        tv_zjm = (TextView) findViewById(R.id.tv_zjm);
        tv_name = (TextView) findViewById(R.id.tv_name);
        tv_type = (TextView) findViewById(R.id.tv_type);
        tv_vender = (TextView) findViewById(R.id.tv_vender);
        tv_sale_unit = (TextView) findViewById(R.id.tv_sale_unit);
        tv_purchase_unit = (TextView) findViewById(R.id.tv_purchase_unit);
        tv_min_package_unit = (TextView) findViewById(R.id.tv_min_package_unit);
        tv_conversion_relation = (TextView) findViewById(R.id.tv_conversion);
        ll_conversion = (RelativeLayout) findViewById(R.id.ll_conversion);
        tv_bzq = (TextView) findViewById(R.id.tv_bzq);
        tv_clw = (TextView) findViewById(R.id.tv_clw);
        tv_stock = (TextView) findViewById(R.id.tv_stock);
        tv_unit = (TextView) findViewById(R.id.tv_unit);
        tv_cost = (TextView) findViewById(R.id.tv_cost);
        tv_purchase_price_specifications = (TextView) findViewById(R.id.tv_purchase_price_specifications);
        tv_price = (TextView) findViewById(R.id.tv_price);
        tv_price_specifications = (TextView) findViewById(R.id.tv_price_specifications);
        tv_return_money = (TextView) findViewById(R.id.tv_return_money);
        tv_discount = (TextView) findViewById(R.id.tv_discount);
        tv_gross_profit = (TextView) findViewById(R.id.tv_gross_profit);
        tv_ljyq = (TextView) findViewById(R.id.tv_ljyq);
        tv_stock_call = (TextView) findViewById(R.id.tv_stock_call);
        tv_buhuo = (TextView) findViewById(R.id.tv_buhuo);
        tv_buhuo.setOnClickListener(this);
        tv_pandian = (TextView) findViewById(R.id.tv_pandian);
        tv_pandian.setOnClickListener(this);
        tv_kaishou = (TextView) findViewById(R.id.tv_kaishou);
        tv_kaishou.setOnClickListener(this);
        tvTitle = (TextView) findViewById(R.id.tvTitle);
        tvTitle.setOnClickListener(this);
        public_ll_return = (ImageView) findViewById(R.id.public_ll_return);
        public_ll_return.setOnClickListener(this);
        cb_weight = (CheckBox) findViewById(R.id.cb_weight);
        cb_weight.setClickable(false);
        public_tv_right = (TextView) findViewById(R.id.public_tv_right);
        public_tv_right.setText("编辑");
        public_tv_right.setOnClickListener(this);
        sw_to_ad_recommend = (EaseSwitchButton) findViewById(R.id.sw_to_ad_recommend);
        rv_show_goods_pic = (RecyclerView) findViewById(R.id.rv_show_goods_pic);
        rv_show_goods_pic.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.public_tv_right:
                if (goodsDetailsNewBean != null) {
                    Intent intent2 = new Intent(this, GoodEditActivity.class);
                    intent2.putExtra("bean", (Serializable) goodsDetailsNewBean);
                    intent2.putExtra("item_store_id", item_store_id);
                    startActivity(intent2);
                }
                break;
            case R.id.public_ll_return:
                finish();
                break;
            case R.id.tv_buhuo:
                if (goodsDetailsNewBean == null) {
                    break;
                }
                Intent intent = new Intent(this, GoodReplenishmentActivity.class);
                intent.putExtra("zbm", goodsDetailsNewBean.getQuick_code());
                intent.putExtra("barcode", goodsDetailsNewBean.getBarcode());
                intent.putExtra("goods_name", goodsDetailsNewBean.getGoods_name());
                intent.putExtra("price", goodsDetailsNewBean.getMarket_price());
                intent.putExtra("price_specifications", goodsDetailsNewBean.getSale_unit());
                intent.putExtra("purchase_price_specifications", goodsDetailsNewBean.getPurchase_unit());
                intent.putExtra("unit", goodsDetailsNewBean.getSale_unit());
                intent.putExtra("bzq", goodsDetailsNewBean.getDurability_period());
                intent.putExtra("pcm", "");
                intent.putExtra("clw", goodsDetailsNewBean.getWarehouse());
                intent.putExtra("stores_goods_id", item_store_id);
                intent.putExtra("pic_detail_info_url", goodsDetailsNewBean.getPic_detail_info_url());
                startActivity(intent);
                break;
            case R.id.tv_pandian:
                Intent intent5 = new Intent();
                intent5.setClass(GoodDetailsNewActivity.this, WebViewTGActivity.class);
                intent5.putExtra("title", "盘点");
                intent5.putExtra("url", SettingData.http + SettingData.pandianURL2 + "stores_id="+ MainActivity.member_id+"&goods_id="+item_store_id);
                startActivity(intent5);
                break;
            case R.id.tv_kaishou:
                if (tv_kaishou.getText().equals("开售")) {
                    netRequest.requestGoodsEditIsoffline(1, "N", item_store_id);
                } else {
                    netRequest.requestGoodsEditIsoffline(1, "Y", item_store_id);
                }
                break;
            case R.id.sw_to_ad_recommend:
                break;
        }
    }


    @Override
    public void onAfinalFail() {
        dismissProgressDialog();
    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        dismissProgressDialog();
        if (requestId == 4) {
            try {
                JSONObject jsonObject = new JSONObject(result);
                Gson gson = new Gson();
                goodsDetailsNewBean = gson.fromJson(jsonObject.getString("detail").toString(), GoodsDetailsNewBean.class);
                Log.d("xgp", goodsDetailsNewBean.toString());
                JSONArray jsonArray = new JSONArray(goodsDetailsNewBean.getPic_detail_info_url());
                mUploadBitmapBeans.clear();
                for (int i = 0; i < jsonArray.length(); i++) {
                    BitmapBean bitmapBean = new BitmapBean();
                    if(jsonArray.getJSONObject(i).toString().equals("{}")){
                        continue;
                    }
                    if(jsonArray.getJSONObject(i).getString("path")!=null){
                        bitmapBean.setDoc_path(jsonArray.getJSONObject(i).getString("path"));
                        mUploadBitmapBeans.add(bitmapBean);
                    }
                    Log.v("zyl", "bitmapBean doc_path：" + bitmapBean.getDoc_path());

                }
                mAddGoodsRVAdapter.notifyDataSetChanged();
                refreshUi(goodsDetailsNewBean);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (requestId == 1) {
            if (tv_kaishou.getText().equals("开售")) {
                tv_kaishou.setText("停售");
            } else {
                tv_kaishou.setText("开售");
            }
        }
    }

    public void refreshUi(GoodsDetailsNewBean goodsDetailsNewBean) {
       /* goodsDetailsNewBean.setPurchase_unit("箱");
        goodsDetailsNewBean.setSale_unit("包");
        goodsDetailsNewBean.setMin_pack_unit("支");
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("purchase_unit", "1");
            jsonObject.put("sale_unit", "6");
            jsonObject.put("min_pack_unit", "72");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        goodsDetailsNewBean.setConversion_relation(jsonObject.toString());*/
        tv_ljyq.setText(goodsDetailsNewBean.getExpired_warning());//临期预警
        float grossProfit = Float.parseFloat(goodsDetailsNewBean.getGross_profit()) * 100;
        tv_gross_profit.setText(String.valueOf(grossProfit));//毛利
        tv_purchase_price_specifications.setText(goodsDetailsNewBean.getPurchase_unit());//进价规格取的是采购单位
        tv_price_specifications.setText(goodsDetailsNewBean.getSale_unit());//售价规格取的是销售单位
        tv_unit.setText(goodsDetailsNewBean.getSale_unit());//库存单位取的是销售单位
        tv_clw.setText(goodsDetailsNewBean.getWarehouse());
        tv_sale_unit.setText(goodsDetailsNewBean.getSale_unit());
        tv_purchase_unit.setText(goodsDetailsNewBean.getPurchase_unit());
        tv_min_package_unit.setText(goodsDetailsNewBean.getMin_pack_unit());
//        tv_conversion_relation.setText(goodsDetailsNewBean.getConversion_relation());
        showConversionText(goodsDetailsNewBean.getConversion_relation(), goodsDetailsNewBean.getPurchase_unit(), goodsDetailsNewBean.getSale_unit(), goodsDetailsNewBean.getMin_pack_unit());
        tv_zjm.setText(goodsDetailsNewBean.getQuick_code());
        tv_zbm.setText(goodsDetailsNewBean.getGoods_code());
        tv_barcode.setText(goodsDetailsNewBean.getBarcode());
        tv_name.setText(goodsDetailsNewBean.getGoods_name());
//        et_spec.setText(goodsDetailsNewBean.getSpecification());
        tv_stock.setText(goodsDetailsNewBean.getSale_qty());
        tv_stock_call.setText(goodsDetailsNewBean.getStock_warning());
        tv_price.setText(goodsDetailsNewBean.getMarket_price());
        tv_cost.setText(goodsDetailsNewBean.getCost_price());
        tv_vender.setText(goodsDetailsNewBean.getManufacturer());
//        tv_expiration_date.setText(goodsDetailsNewBean.getProduction_date());
        tv_bzq.setText(goodsDetailsNewBean.getDurability_period());
//        tv_dealer.setText(goodsDetailsNewBean.getSupplier());
//        tv_data_input.setText(goodsDetailsNewBean.getProduct_source());
        tv_return_money.setText(goodsDetailsNewBean.getRebate());
        tv_type.setText(goodsDetailsNewBean.getCategory());
        //称重计量
        if (goodsDetailsNewBean.getIs_weighed().equals("Y")) {
            cb_weight.setChecked(true);
        } else {
            cb_weight.setChecked(false);
        }
        //广告推荐
        if (goodsDetailsNewBean.getIs_recommend().equals("Y")) {
            sw_to_ad_recommend.openSwitch();
        } else {
            sw_to_ad_recommend.closeSwitch();
        }
        //收银
        if (goodsDetailsNewBean.getIs_show().equals("Y")) {
            sw_to_cashier.openSwitch();
        } else {
            sw_to_cashier.closeSwitch();
        }
        //网店
        if (goodsDetailsNewBean.getIs_sell().equals("Y")) {
            sw_to_local_life.openSwitch();
        } else {
            sw_to_local_life.closeSwitch();
        }
//        //推荐
//        if (goodsDetailsNewBean.getIs_recommend().equals("Y")) {
//            cb_recommend.setChecked(true);
//        } else {
//            cb_recommend.setChecked(false);
//        }
        //折扣
        if (goodsDetailsNewBean.getIs_activity().equals("Y")) {
            sw_discount.openSwitch();
        } else {
            Log.v("zyl", "没有选择折扣");
            sw_discount.closeSwitch();
        }
        //停止销售
        if (goodsDetailsNewBean.getIs_offline().equals("Y")) {
            tv_kaishou.setText("停售");
        } else {
            tv_kaishou.setText("开售");
        }

    }

    //显示换算关系
    private void showConversionText(String conversion_relation, String cgdwNum, String xsdwNum, String zxbzNum) {
        try {
            JSONObject jsonObject = new JSONObject(conversion_relation);
            String mPurchaseUnit = jsonObject.getString("purchase_unit");
            String mSaleUnit = jsonObject.getString("sale_unit");
            String mMinPackageUnit = jsonObject.getString("min_pack_unit");
            tv_conversion_relation.setText(mPurchaseUnit + cgdwNum + "=" + mSaleUnit + xsdwNum + "=" + mMinPackageUnit + zxbzNum);
        } catch (Exception e) {
            tv_conversion_relation.setText("");
            e.printStackTrace();
        }

    }

    @Override
    public void onExecuteFail(int requestId, String msg) {
        showToast(msg);
        dismissProgressDialog();
    }


}
